#!/bin/bash

# SSH远程控制工具中继服务器部署脚本

# 1.2 服务器初始化
echo "更新系统并安装基础软件..."
sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-pip python3-venv git nginx
sudo useradd -m -s /bin/bash sshrelay
sudo usermod -aG sudo sshrelay

# 1.3 部署中继服务器
echo "复制项目文件并修改所有者..."
# 请手动将ssh-remote-tool/relay-server目录复制到/home/sshrelay/
# scp -r /path/to/your/ssh-remote-tool/relay-server ubuntu@<YOUR_SERVER_IP>:/home/sshrelay/
sudo chown -R sshrelay:sshrelay /home/sshrelay/relay-server

echo "创建虚拟环境并安装依赖..."
sudo su - sshrelay -c "cd /home/sshrelay/relay-server && python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt && pip install gunicorn"

echo "创建Gunicorn配置文件..."
sudo su - sshrelay -c "cat > /home/sshrelay/relay-server/gunicorn.conf.py << EOF
bind = \"127.0.0.1:5001\"
workers = 4
worker_class = \"sync\"
timeout = 30
keepalive = 2
max_requests = 1000
max_requests_jitter = 100
preload_app = True
EOF"

echo "创建systemd服务文件..."
echo "[Unit]
Description=SSH Relay Server
After=network.target

[Service]
Type=notify
User=sshrelay
Group=sshrelay
WorkingDirectory=/home/sshrelay/relay-server
Environment=PATH=/home/sshrelay/relay-server/venv/bin
ExecStart=/home/sshrelay/relay-server/venv/bin/gunicorn -c /home/sshrelay/relay-server/gunicorn.conf.py src.main:app
ExecReload=/bin/kill -s HUP \$MAINPID
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/ssh-relay.service

echo "启动服务..."
sudo systemctl daemon-reload
sudo systemctl enable ssh-relay
sudo systemctl start ssh-relay
sudo systemctl status ssh-relay

# 1.4 配置Nginx反向代理
echo "配置Nginx反向代理..."
echo "server {
    listen 80;
    server_name <YOUR_SERVER_IP_OR_DOMAIN>; # 替换为您的服务器IP地址或域名

    location / {
        proxy_pass http://127.0.0.1:5001;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}" | sudo tee /etc/nginx/sites-available/ssh-relay

sudo ln -s /etc/nginx/sites-available/ssh-relay /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

# 1.5 防火墙配置
echo "配置UFW防火墙..."
sudo ufw allow ssh
sudo ufw allow 'Nginx Full'
sudo ufw allow 8000:9000/tcp
sudo ufw enable

echo "服务器安装脚本执行完毕。请根据提示手动复制项目文件并替换IP地址或域名。"


